package com.ungao.framework.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * JDK代理类
 * 代理接口
 *
 * @author vic-ungao
 */
public class JdkProxy implements ProxyFactory, InvocationHandler {

    /**
     * 代理目标对象
     */
    protected Object target;

    @Override
    public <T> T getProxy(T target) {
        throw new RuntimeException("The method cannot be called!");
    }

    @Override
    public <T> T getProxy(Class<T> target) throws IllegalAccessException, InstantiationException {
        throw new RuntimeException("The method cannot be called!");
    }

    @Override
    public <R, T extends R> R getProxy(Class<R> clazz, T target) {
        this.target = target;
        return (R) Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz}, this);
    }

    @Override
    public <R, T extends R> R getProxy(Class<R> clazz, Class<T> target) throws IllegalAccessException, InstantiationException {
        this.target = target.newInstance();
        return (R) Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz}, this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        return method.invoke(target, args);
    }
}
